package com.lw.sbdemo2.common.exception;

import com.lw.sbdemo2.common.vo.ResultModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>标题: 全局异常处理</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2018</p>
 * <p>公司: 智业软件</p>
 *
 * @author LinWang
 * @date 2018-02-10 9:16
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Throwable.class)
    public ResultModel jsonErrorHandler(HttpServletRequest req, Throwable e) throws Exception {
        log.error("请求发生异常，URL：{}，HTTP_METHOD：{}，IP：{}，错误信息：{}", req.getRequestURL().toString(),
                req.getMethod(), req.getRemoteAddr(), e.getMessage());
        ResultModel resultModel;

        if (e instanceof ApiException) {
            resultModel = ResultModel.fail(((ApiException) e).getCode().getCode(),
                    ((ApiException) e).getErrorMessage(),
                    ((ApiException) e).getCode().getMessage());
        } else if (e instanceof NoHandlerFoundException) {
            resultModel = ResultModel.fail(ResponseCodeEnum.EX_PAGE_404, e.getMessage());
        } else {
            resultModel = ResultModel.fail(ResultModel.ERROR_CODE,
                    null,
                    e.getMessage());
        }
        return resultModel;
    }
}